package com.lyf.common.utils;


import com.lyf.common.exception.ApiException;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author lyf
 * @date 2020/11/21 15:08
 */
public class NumberUtil {
    /**
     * 用于随机选的数字
     */
    public static final String BASE_NUMBER = "0123456789";
    /**
     * 用于随机选的字符
     */
    public static final String BASE_CHAR = "abcdefghijklmnopqrstuvwxyz";

    public static final String BASE_NUMBER_CHAR = BASE_NUMBER + BASE_CHAR;

    /**
     * 随机生成指定位数的数字字符串
     * @param n
     * @return
     */
    public static String generate(int n) {
        Random rand = new Random();
        StringBuffer flag = new StringBuffer();
        for (int j = 0; j < n; j++) {
            flag.append(BASE_NUMBER.charAt(rand.nextInt(9)) + "");
        }
        return flag.toString();
    }

    /**
     * 返回随机字符串，同时包含数字、字母
     *
     * @param len 字符串长度，不能小于2
     * @return String 随机字符串
     */
    public static String randomStr(int len) {
        if (len < 2) {
            throw new ApiException("随机字符串长度不能小于2");
        }
        //数组，用于存放随机字符
        char[] chArr = new char[len];
        Random random = new Random();
        //为了保证必须包含数字、字母
        chArr[0] = BASE_NUMBER.charAt(random.nextInt(BASE_NUMBER.length()));
        chArr[1] = BASE_CHAR.charAt(random.nextInt(BASE_CHAR.length()));


        //charArr[2..len-1]随机生成codes中的字符
        for (int i = 2; i < len; i++) {
            chArr[i] = BASE_NUMBER_CHAR.charAt(random.nextInt(BASE_NUMBER_CHAR.length()));
        }

        //将数组chArr随机排序
        for (int i = 0; i < len; i++) {
            int r = i + random.nextInt(len - i);
            char temp = chArr[i];
            chArr[i] = chArr[r];
            chArr[r] = temp;
        }
        return new String(chArr);
    }

    /**
     * 生成指定数量 指定位数的随机数   包含数字和字母
     * @param length
     * @param num
     * @return
     */
    public static List<String> getCodes(int length, int num) {
        List<String> list = new ArrayList<>();
        if (num == 0) {
            return list;
        }
        for (int i = 0; i < num; i++) {
            list.add(randomStr(length).toUpperCase());
        }
        return list;
    }
}